package com.buer.service.util;

import com.buer.service.exception.AppException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class IoUtil {
    public static void createText(String path, String fileName, String content) {
        File fileDir = new File(path);
        fileDir.mkdirs();
        createText(path + fileName, content);
    }

    public static String readToString(String path, String fileName) {
        File file = new File(path + fileName);
        if (!file.exists()) throw new AppException("文件不存在，path:" + path + ";fileName" + fileName);
        return readToString(file);
    }

    public static String readToString(File file) {
        Long filelength = file.length();     //获取文件长度
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(filecontent);//返回文件内容,默认编码
    }

    public static void createText(String fileName, String content) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {

            File file = new File(fileName);
            // create the file if doesn't exists
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

        } catch (IOException e) {
            System.out.println("IO Problem");
        } finally {
            try {
                if (null != bw) {
                    bw.close();
                }
                if (null != fw) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static BufferedReader openFile(String path, String fileName) {
        if (!path.endsWith(File.separator)) path = path + File.separator;
        return openFile(path + fileName);
    }

    public static BufferedReader openFile(String fileName) {
//            System.out.println(new File(".").getAbsoluteFile());
        File file = new File(fileName);
//            System.out.println(file.exists());
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return br;
    }
}

